package com.sdx.console.wx;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * http工具类
 *
 * @author tanbaocai
 * @create 2018-05-20 21:18
 **/
public class HttpUtils {
	private static final Logger log = LoggerFactory.getLogger("HttpUtils");

	/**
	 * post请求
	 * @param url 请求url
	 * @param content post内容体
	 * @return 返回响应字符串
	 * @throws IOException
	 */
	public static String httpPost(String url, String content) throws IOException {

		log.info(url);
		log.info("post "+content);
		URL url_news = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) url_news.openConnection();
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.connect();
		StringBuffer strBuff = new StringBuffer();
		try (
				OutputStream os = conn.getOutputStream()
		) {
			os.write(content.getBytes("utf-8"));
			os.flush();
		}
		try (
				BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"))
		) {
			String line = in.readLine();
			while(line!=null) {
				strBuff.append(line);
				line = in.readLine();
			}
		}
		log.info("response "+strBuff.toString());
		return strBuff.toString();
	}

	public static String httpGet(String url) throws IOException {

		log.info(url);

		URL url_news = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) url_news.openConnection();
		conn.setRequestMethod("GET");
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.connect();
		StringBuffer strBuff = new StringBuffer();
		try (
				BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"))
		) {
			String line = in.readLine();
			while(line!=null) {
				strBuff.append(line);
				line = in.readLine();
			}
		}
		log.info("response "+strBuff.toString());
		return strBuff.toString();
	}
}
